package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Client;
import cn.wolfcode.crm.domain.ClientDevPlan;
import cn.wolfcode.crm.domain.FailPlanList;
import cn.wolfcode.crm.mapper.ClientDevPlanMapper;
import cn.wolfcode.crm.query.ClientPlanQueryObject;
import cn.wolfcode.crm.service.IClientDevPlanService;
import cn.wolfcode.crm.service.IClientService;
import cn.wolfcode.crm.service.IFailPlanListService;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ClientDevPlanServiceImpl implements IClientDevPlanService {
    @Autowired
    private ClientDevPlanMapper mapper;
    @Autowired
    private IClientService clientService;
    @Autowired
    private IFailPlanListService failPlanListService;

    public List<ClientDevPlan> selectAll() {
        return mapper.selectAll();
    }

    public PageResult query(ClientPlanQueryObject qo) {
        int count = mapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, mapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    public void updateByPrimaryKey(ClientDevPlan record) {
        mapper.updateByPrimaryKey(record);
    }

    public ClientDevPlan getByName(String name) {
        return mapper.getByName(name);
    }

    public void insert(ClientDevPlan record) {
        record.setInputTime(new Date());
        record.setInputUser(UserContext.getCurrentUser());
        mapper.insert(record);
    }

    public void changeResult(Long id,Long result) {
        mapper.changeResult(id,result);
    }

    public Long selectByUserName(String name) {
        return mapper.selectByUserName(name);
    }

    public ClientDevPlan selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void developmentFailed(Long cid) {
        ClientDevPlan clientDevPlan = mapper.selectByClientId(cid);
        if (clientDevPlan==null){
            throw new LogicException("还没开发,不能开发失败");
        }
        Client client = clientService.selectByPrimaryKey(cid);
        FailPlanList fpl = new FailPlanList();
        fpl.setFailTime(new Date());
        fpl.setFailClient(client);
        fpl.setChargeUser(client.getInChargeUser());
        fpl.setDetail("开发失败简介");
        clientService.changeStatus(-1L,cid);
        failPlanListService.insert(fpl);
        mapper.deleteByClientId(cid);
    }
}
